package com.ewzj.bigdata.mvp.ui.activity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.ewzj.bigdata.R;
import com.ewzj.bigdata.app.MyGlideEngine;
import com.ewzj.bigdata.app.constants.AppConstants;
import com.ewzj.bigdata.app.utils.Apputils;
import com.ewzj.bigdata.app.utils.RegexUtils;
import com.ewzj.bigdata.app.utils.UriToPathUtil;
import com.ewzj.bigdata.di.component.DaggerEditProfileComponent;
import com.ewzj.bigdata.di.module.EditProfileModule;
import com.ewzj.bigdata.mvp.contract.EditProfileContract;
import com.ewzj.bigdata.mvp.model.entity.resbean.UserBean;
import com.ewzj.bigdata.mvp.presenter.EditProfilePresenter;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.http.imageloader.glide.ImageConfigImpl;
import com.jess.arms.utils.ArmsUtils;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.view.listener.OnInputClickListener;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class EditProfileActivity extends BaseActivity<EditProfilePresenter> implements EditProfileContract.View {


    @BindView(R.id.iv_confirm)
    ImageView ivConfirm;
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.tv_nickname)
    TextView tvNickname;
    @BindView(R.id.tv_mail)
    TextView tvMail;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.rl_location)
    RelativeLayout rlLocation;
    List<Uri> mSelected;
    final int REQUEST_CODE_CHOOSE = 16787;
    private UserBean userBean;

    @Override
    public void setupActivityComponent(AppComponent appComponent) {
        DaggerEditProfileComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .editProfileModule(new EditProfileModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(Bundle savedInstanceState) {
        return R.layout.activity_editprofile; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        userBean = getIntent().getParcelableExtra(AppConstants.EXTRA_DATA);
        ivConfirm.setVisibility(View.VISIBLE);
        initUserInfo(userBean);
    }

    private void initUserInfo(UserBean userBean) {
        if (!TextUtils.isEmpty(userBean.getAvatar())) {
            ArmsUtils.obtainAppComponentFromContext(this).imageLoader().loadImage(this,
                    ImageConfigImpl.builder().imageView(ivHead)
//                            .errorPic(R.drawable.icon_head_default)
                            .placeholder(R.drawable.icon_head_default)
                            .url(Apputils.getFromatUrl(userBean.getAvatar())).build());
        }
        tvNickname.setText(TextUtils.isEmpty(userBean.getNickname()) ? getString(R.string.userdefault_name) : userBean.getNickname());
        tvMail.setText(TextUtils.isEmpty(userBean.getEmail()) ? getString(R.string.userbinding_empty) : userBean.getEmail());
        tvPhone.setText(TextUtils.isEmpty(userBean.getMobile()) ? getString(R.string.userbinding_empty) : userBean.getMobile());
        tvSex.setText(TextUtils.isEmpty(userBean.getGender()) ? "男" : userBean.getGender());
        tvLocation.setText(TextUtils.isEmpty(userBean.getCity_name()) ? getString(R.string.usercity_empty) : userBean.getCity_name());
    }


    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @OnClick({R.id.iv_confirm, R.id.rl_head, R.id.rl_nickname, R.id.rl_mail, R.id.rl_phone, R.id.rl_sex, R.id.rl_location})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_confirm:
                mPresenter.updateUserInfo(userBean);
                break;
            case R.id.rl_head:
                showPicSelected();
                break;
            case R.id.rl_nickname:
                showUpdateDialog("设置昵称", tvNickname);
                break;
            case R.id.rl_mail:
                showUpdateDialog("绑定邮箱", tvMail);
                break;
            case R.id.rl_phone:
                showUpdateDialog("绑定电话号码", tvPhone);
                break;
            case R.id.rl_sex:
                sexUpdateDialog();
                break;
            case R.id.rl_location:
                showUpdateDialog("设置地区", tvLocation);
                break;
        }
    }

    private void showPicSelected() {
        Matisse.from(this)
                .choose(MimeType.allOf())
                .countable(true)
                .maxSelectable(1)
                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_USER)
                .thumbnailScale(0.85f)
                .imageEngine(new MyGlideEngine())
                .forResult(REQUEST_CODE_CHOOSE);
    }

    private void showUpdateDialog(String title, TextView textView) {
        new CircleDialog.Builder(this).setCanceledOnTouchOutside(false)
                .setCancelable(true)
                .setTitle(title)
                .setInputHint(textView.getText().toString())
                .setNegative("取消", null)
                .setPositiveInput("确定", new OnInputClickListener() {
                    @Override
                    public void onClick(String text, View v) {
                        if ("绑定邮箱".equals(title)) {
                            if (RegexUtils.checkEmail(text)) {
                                textView.setText(text);
                                userBean.setEmail(text);
                            } else {
                                ArmsUtils.snackbarText("邮箱格式不正确");
                                return;
                            }

                        } else {
                            textView.setText(text);
                        }

                    }
                }).show();
    }

    private void sexUpdateDialog() {
        SexSelectActivity.show(this, TextUtils.isEmpty(userBean.getGender()) ? "男" : userBean.getGender());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            mSelected = Matisse.obtainResult(data);
            ArmsUtils.obtainAppComponentFromContext(this).imageLoader().loadImage(this,
                    ImageConfigImpl.builder().imageView(ivHead)
                            .transformation(new CircleCrop())
                            .errorPic(R.drawable.icon_head_default)
                            .placeholder(R.drawable.icon_head_default)
                            .url(mSelected.get(0).toString()).build());
            mPresenter.uploadFile(UriToPathUtil.getImageAbsolutePath(this, mSelected.get(0)));
            Log.d("Matisse", "mSelected: " + mSelected);
        } else if (requestCode == 0x12 && resultCode == RESULT_OK) {
            String sex = data.getStringExtra(AppConstants.EXTRA_DATA);
            userBean.setGender(sex);
            tvSex.setText(sex);
        }
    }

    @Override
    public void setUserImg(String img) {
        if (TextUtils.isEmpty(img) || userBean == null) {
            return;
        }
        userBean.setAvatar(img);
    }

    @Override
    public void setUploadProgress(int progress) {

    }

    @Override
    protected void onDestroy() {
        mPresenter.cancelUpload();
        super.onDestroy();
    }

}
